$(function () {
    $("#jqGrid").Grid({
        url: '../specialdevlift/list',
        shrinkToFit:false,
        autoScroll: true, //开启水平滚动条
        colModel: [
            {label: '设备编号', name: 'equipmentCode', index: 'EQUIPMENT_CODE', width: 90},
            {label: '设备名称', name: 'devName', index: 'DEV_NAME', width: 90},
            {label: '设备型号', name: 'model', index: 'MODEL', width: 80},
            {label: '出厂编号', name: 'productNo', index: 'PRODUCT_NO', width: 140},
            {label: '资产编号', name: 'fixedAssetCode', index: 'FIXED_ASSET_CODE', width: 140},
            {label: '注册代码', name: 'registCode', index: 'REGIST_CODE', width: 80},
            {label: '设备代码', name: 'devCode', index: 'DEV_CODE', width: 160},
            {label: '使用登记证编号', name: 'registCertCode', index: 'REGIST_CERT_CODE', width: 120},
            {label: '安装日期', name: 'installDate', index: 'INSTALL_DATE', width: 100,
                formatter: function (v) {
                    return transDate(v, 'yyyy-MM-dd')
                }
            },
            {label: '生产厂家', name: 'factoryName', index: 'FACTORY', width: 80},
            {label: '使用单位', name: 'userDeptName', index: 'USER_DEPT', width: 80},
            {label: '使用地点', name: 'location', index: 'LOCATION', width: 80},
            {label: '使用状况', name: 'state', index: 'STATE', width: 80},
            {
                label: '最近检验日期', name: 'latestInspectDate', index: 'LATEST_INSPECT_DATE', width: 100,
                formatter: function (v) {
                    return transDate(v, 'yyyy-MM-dd')
                }
            },
            {
                label: '下次检测时间', name: 'nextInspectDate', sortable: false, width: 100,
                formatter: function (v) {
                    return transDate(v, 'yyyy-MM-dd')
                }
            },
            {
                label: '校验记录', width: 80, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='查看' class='btn btn-outline btn-info' onclick='vm.viewCheckRecord(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}]
    });
    // 初始化使用部门树
    vm.initUserDept();
});
// 使用部门树配置
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        beforeCheck: true
    }
};

//设备组织树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    vm.q.userDept = treeObj.deptId;
    vm.query();
}
var ztree,deptZtree;
let vm = new Vue({
    el: '#rrapp',
    data: {
        treeList: [], // 使用单位列表
        showList: true,
        title: null,
        specialDevLift: {
            selfCode: '',
            state: '',
            installDate: '',
            factory: '',
            factoryName: '',
            devCode: '',
            registCertCode: '',
            fixedAssetCode: '',
            productNo: '',
            latestInspectDate: '',
            inspectInterval: '',
            inspectIntervalStr: '',
            userDept: '',
            userDeptName: '',
            model: '',
            devName: '',
            id: '',
            registCode: '',
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            devName: '',
            userDept: ''
        }
    },
    methods: {
        // 查看设备档案资料
        addEqu: function () {
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 设备档案',
                content: '../sys/ermsfile.html?moduleType=6&id=' + id
            })
        },
        loadFacType:function(){
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 请选择生产厂家',
                content: '../sys/factorytype_choose.html?type=0',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.specialDevLift.factory = res.id;
                        vm.specialDevLift.factoryName = res.faName;
                    }
                }
            })
        },
        // 初始化使用部门树
        initUserDept: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCXLevel?level=2',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                    deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
                    deptZtree.expandAll(true);
                }
            });
        },
        // 显示使用部门列表
        showUserDeptList: function () {
            openWindow({
                title: "请选择使用单位",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var selectedNodes = ztree.getSelectedNodes();
                    if (selectedNodes.length == 0) {
                        alert("请选择使用部门");
                        return
                    }
                    vm.specialDevLift.userDept = selectedNodes[0].deptId;
                    vm.specialDevLift.userDeptName = selectedNodes[0].name;
                    layer.close(index);
                }
            });
        },
        // 初始化使用部门选择树
        initUserDeptSelect: function () {
            //加载分类树
            ztree = $.fn.zTree.init($("#categoryTree"), setting, vm.treeList);
            ztree.expandAll(true);
            var node = ztree.getNodeByParam("deptId", vm.specialDevLift.userDept);
            if (node) {
                ztree.selectNode(node);
                vm.specialDevLift.userDeptName = node.name;
                ztree.expandNode(node);
            } else {
                node = ztree.getNodeByParam("deptId", "0");
                ztree.selectNode(node);
            }
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.specialDevLift = {
                selfCode: '',
                state: '',
                installDate: '',
                factory: '',
                devCode: '',
                registCertCode: '',
                fixedAssetCode: '',
                productNo: '',
                latestInspectDate: '',
                inspectInterval: '',
                userDept: '',
                userDeptName: '',
                model: '',
                devName: '',
                id: '',
                registCode: '',
            };
            vm.initUserDeptSelect();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
            vm.initUserDeptSelect();
        },
        saveOrUpdate: function (event) {
            let url = vm.specialDevLift.id == (null || '') ? "../specialdevlift/save" : "../specialdevlift/update";
            if(vm.specialDevLift.inspectIntervalStr){
                vm.specialDevLift.inspectInterval = parseInt(vm.specialDevLift.inspectIntervalStr);
            }
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.specialDevLift),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../specialdevlift/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../specialdevlift/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.specialDevLift = r.specialDevLift;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var queryParam = {};
            if (vm.q.devName) {
                queryParam.devName = vm.q.devName;
            }
            if (vm.q.userDept) {
                queryParam.userDept = vm.q.userDept;
            }
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: queryParam,
                page: page
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q = {
                devName: '',
                userDept: ''
            };
            deptZtree.cancelSelectedNode();
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        viewCheckRecord: function (id) {
            // 查看电梯校验记录
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 校验记录',
                content: '../device/specialdevcheckrecord.html?devId=' + id + '&devType=LIFT'
            })
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        exportData: function () {
            window.open('../specialdevlift/export', '_blank');
        }
    }
});
